import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:kasax/utils/color_utils.dart';

class PageViewDemo2 extends StatefulWidget {
  const PageViewDemo2({Key? key}) : super(key: key);

  @override
  _PageViewDemo2State createState() => _PageViewDemo2State();
}

class _PageViewDemo2State extends State<PageViewDemo2> {
  @override
  Widget build(BuildContext context) {
    return PageView03Demo();
  }
}

class PageView03Demo extends StatefulWidget {
  const PageView03Demo({Key? key}) : super(key: key);

  @override
  _PageView03DemoState createState() => _PageView03DemoState();
}

class _PageView03DemoState extends State<PageView03Demo> {
  List<String> items = <String>['1', '2', '3', '4', '5'];

  @override
  void initState() {
    super.initState();
  }

  _reverse() {
    setState(() {
      items = items.reversed.toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("PageView"),
      ),
      body: SizedBox(
        height: 250,
        child: PageView.custom(
            childrenDelegate: SliverChildBuilderDelegate(
                (context, index) {
                  return KeepAlive(
                    data: items[index],
                    bgColor: buildRandomColor(),
                    key: ValueKey<String>(items[index]),
                  );
                },
                childCount: items.length,
                findChildIndexCallback: (key) {
                  var tarkey = key as ValueKey<String>;
                  String keyData = tarkey.value;
                  print("findChildIndexCallback keyData:$keyData");
                  return items.indexOf(keyData);
                })),
      ),
      bottomNavigationBar: BottomAppBar(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextButton(
              onPressed: _reverse(),
              child: Text("Reverse items"),
            )
          ],
        ),
      ),
    );
  }
}

class KeepAlive extends StatefulWidget {
  const KeepAlive({Key? key, required this.data, required this.bgColor})
      : super(key: key);

  final String data;
  final Color bgColor;

  @override
  _KeepAliveState createState() => _KeepAliveState();
}

class _KeepAliveState extends State<KeepAlive>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      color: widget.bgColor,
      child: Text(
        widget.data,
        style: TextStyle(fontSize: 32, color: Colors.white),
      ),
    );
  }
}
